package com.ruoyi.basicsystem.service.impl;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.basicsystem.domain.ZnAgreement;
import com.ruoyi.basicsystem.domain.ZnDepot;
import com.ruoyi.basicsystem.mapper.ZnAgreementMapper;
import com.ruoyi.basicsystem.service.IZnAgreementService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SaveBusinessVO;
import com.ruoyi.system.domain.ZnCompanyConfig;
import com.ruoyi.system.domain.ZnUserBusiness;
import com.ruoyi.system.service.IZnCompanyConfigService;
import com.ruoyi.system.service.IZnUserBusinessService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.basicsystem.mapper.ZnSupplierMapper;
import com.ruoyi.basicsystem.domain.ZnSupplier;
import com.ruoyi.basicsystem.service.IZnSupplierService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 供应商/客户/会员信息Service业务层处理
 * 
 * @author nexiaozi
 * @date 2022-02-16
 */
@Service
public class ZnSupplierServiceImpl implements IZnSupplierService
{
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private ZnSupplierMapper znSupplierMapper;
    @Autowired
    private IZnCompanyConfigService znCompanyConfigService;
    @Autowired
    private IZnUserBusinessService znUserBusinessService;
    @Autowired
    private ZnAgreementMapper znAgreementMapper;

    /**
     * 查询供应商/客户/会员信息
     * 
     * @param id 供应商/客户/会员信息主键
     * @return 供应商/客户/会员信息
     */
    @Override
    public ZnSupplier selectZnSupplierById(Long id)
    {
        ZnSupplier znSupplier = znSupplierMapper.selectZnSupplierById(id);
        if(znSupplier.getType().equals("客户") && znSupplier.getIsAgree().equals("1")){
            ZnAgreement znAgreement = new ZnAgreement();
            znAgreement.setTenantId(SecurityUtils.getTenantId());
            znAgreement.setCustomerId(id);
            znAgreement.setDeleteFlag("0");
            znAgreement.setStatus("2");
            List<ZnAgreement> agreementList = znAgreementMapper.selectZnAgreementList(znAgreement);
            if(agreementList.size()>0){
                znSupplier.setAgreementId(agreementList.get(0).getParentId());
            }
        }
        return znSupplier;
    }

    /**
     * 查询供应商/客户/会员信息列表
     * 
     * @param znSupplier 供应商/客户/会员信息
     * @return 供应商/客户/会员信息
     */
    @Override
    public List<ZnSupplier> selectZnSupplierList(ZnSupplier znSupplier)
    {
        znSupplier.setTenantId(SecurityUtils.getTenantId());
        znSupplier.setDeleteFlag("0");
        return znSupplierMapper.selectZnSupplierList(znSupplier);
    }

    /**
     * 新增供应商/客户/会员信息
     * 1、新增客户的时候，需要判断是否开启系统配置分配客户，如果有的，需要将客户分配到创建人下。
     * 2、新增客户的时候，按照客户的售价系数，生成当前的协议价,有效期30天
     * @param znSupplier 供应商/客户/会员信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertZnSupplier(ZnSupplier znSupplier)
    {
       if(znSupplier.getType().equals("客户")){
           if(znSupplier.getIsAgree() ==null){
               znSupplier.setIsAgree("0");
           }
        }
        int rows = znSupplierMapper.insertZnSupplier(znSupplier);
        if(rows >0 && znSupplier.getType().equals("客户")){
            ZnCompanyConfig znCompanyConfig=znCompanyConfigService.selectZnCompanyConfigBytenantId(SecurityUtils.getTenantId());
            boolean customerFlag ="1".equals(znCompanyConfig.getCustomerFlag())?true:false; //获取系统配置，是否需要用户需要分配客户，暂时先写false
            if(customerFlag) {
                SaveBusinessVO saveBusinessVO =new SaveBusinessVO();
                saveBusinessVO.setUserId(SecurityUtils.getUserId());
                saveBusinessVO.setType("UserCustomer");
                saveBusinessVO.setTenantId(SecurityUtils.getTenantId());
                ZnUserBusiness znUserBusiness = znUserBusinessService.selectZnUserBusinessByUserIdAndType(saveBusinessVO);
                List<Long> values=new ArrayList<>();
                if(null!=znUserBusiness&&znUserBusiness.getValue()!=null){
                    znUserBusiness.setValue( znUserBusiness.getValue()+","+znSupplier.getId());
                    znUserBusinessService.updateZnUserBusiness(znUserBusiness);
                }else{
                    znUserBusiness = new ZnUserBusiness();
                    BeanUtils.copyProperties(saveBusinessVO,znUserBusiness);
                    znUserBusiness.setValue(znSupplier.getId().toString());
                    znUserBusiness.setDeleteFlag("0");
                    znUserBusinessService.insertZnUserBusiness(znUserBusiness);
                }
            }
            if(!znSupplier.getIsAgree().isEmpty() && znSupplier.getIsAgree().equals("1")){
                if(znSupplier.getAgreementId() !=null){
                    ZnAgreement znAgreement = new ZnAgreement();
                    znAgreement.setCustomerId(znSupplier.getId());
                    znAgreement.setParentId(znSupplier.getAgreementId());
                    znAgreement.setCreateTime(new Date());
                    znAgreement.setCreateBy(SecurityUtils.getUsername());
                    znAgreement.setCreateName(SecurityUtils.getLoginUser().getUser().getNickName());
//                    znAgreement.setIsDefault("1");
                    znAgreement.setDeleteFlag("0");
                    znAgreement.setTenantId(SecurityUtils.getTenantId());
                    znAgreementMapper.insertZnAgreement(znAgreement);
                }else{
                    ZnAgreement znAgreement = new ZnAgreement();
                    znAgreement.setUserId(SecurityUtils.getUserId());
                    znAgreement.setDeptId(SecurityUtils.getDeptId());
                    znAgreement.setTenantId(SecurityUtils.getTenantId());
                    znAgreement.setStatus("2");//默认生效
                    znAgreement.setDeleteFlag("0");
                    znAgreement.setEffectTime(DateUtils.addDays(new Date(),30));
                    znAgreement.setIsDefault("1");
                    znAgreement.setCreateTime(new Date());
                    znAgreement.setCreateBy(SecurityUtils.getUsername());
                    znAgreement.setCreateName(SecurityUtils.getLoginUser().getUser().getNickName());
                    znAgreement.setTitle(znSupplier.getSupplier()+" - 默认协议");
                    znAgreementMapper.insertZnAgreement(znAgreement);
                    ZnAgreement sub = new ZnAgreement();
                    sub.setParentId(znAgreement.getId());
                    sub.setCustomerId(znSupplier.getId());
                    sub.setParentId(znSupplier.getAgreementId());
                    sub.setCreateTime(new Date());
                    sub.setCreateBy(SecurityUtils.getUsername());
                    sub.setCreateName(SecurityUtils.getLoginUser().getUser().getNickName());
                    sub.setIsDefault("1");
                    sub.setDeleteFlag("0");
                    sub.setTenantId(SecurityUtils.getTenantId());
                    znAgreementMapper.insertZnAgreement(sub);
                    Map<String,Object> params = new HashMap<>();
                    params.put("saleRatio",znSupplier.getSaleRatio());
                    znAgreement.setParams(params);
                    znAgreementMapper.batchZnAgreementDetailByZnAgreement(znAgreement);
                }
            }
        }
        return rows;
    }

    /**
     * 修改供应商/客户/会员信息
     * 
     * @param znSupplier 供应商/客户/会员信息
     * @return 结果
     */
    @Override
    public int updateZnSupplier(ZnSupplier znSupplier)
    {
        if(znSupplier.getType().equals("客户")){
            ZnSupplier supplier = znSupplierMapper.selectZnSupplierById(znSupplier.getId());
            ZnAgreement znAgreement= new ZnAgreement();
            znAgreement.setTenantId(SecurityUtils.getTenantId());
            znAgreement.setDeleteFlag("0");
            znAgreement.setCustomerId(znSupplier.getId());
            znAgreement.setParentId(znSupplier.getAgreementId());
            if(znSupplier.getIsAgree().equals("1")){
                if((!znSupplier.getIsAgree().equals(supplier.getIsAgree()))){
                    znAgreement.setCreateName(SecurityUtils.getLoginUser().getUser().getNickName());
                    znAgreement.setCreateBy(SecurityUtils.getUsername());
                    znAgreement.setCreateTime(new Date());
                    znAgreementMapper.insertZnAgreement(znAgreement);
                }else if(znSupplier.getIsAgree().equals(supplier.getIsAgree())){
                    znAgreement.setUpdateName(SecurityUtils.getLoginUser().getUser().getNickName());
                    znAgreement.setUpdateBy(SecurityUtils.getUsername());
                    znAgreement.setUpdateTime(new Date());
                    znAgreementMapper.updateCustomerAgreement(znAgreement);
                }
            }else{
                if((!znSupplier.getIsAgree().equals(supplier.getIsAgree()))){
                    znAgreementMapper.deleteZnAgreementByCustomerIds(new Long[]{supplier.getId()},SecurityUtils.getTenantId());
                }
            }

        }
        return znSupplierMapper.updateZnSupplier(znSupplier);
    }

    /**
     * 批量删除供应商/客户/会员信息
     * 
     * @param ids 需要删除的供应商/客户/会员信息主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteZnSupplierByIds(Long[] ids)
    {
        znAgreementMapper.deleteZnAgreementByCustomerIds(ids,SecurityUtils.getTenantId());
        return znSupplierMapper.deleteZnSupplierByIds(ids);
    }

    /**
     * 删除供应商/客户/会员信息信息
     * 
     * @param id 供应商/客户/会员信息主键
     * @return 结果
     */
    @Override
    public int deleteZnSupplierById(Long id)
    {
        return znSupplierMapper.deleteZnSupplierById(id);
    }
    /**
     * 批量 启用、停用 供应商/客户/会员 状态
     * @param ids
     * @param status 状态
     * @return
     */
    @Override
    public int updateZnSupplierStatusByIds(Long[] ids,String status) {
         return znSupplierMapper.updateZnSupplierStatusByIds(ids,status);
    }

    /**
     * 批量导入 供应商/客户/会员信息
     * @param znSupplierList
     * @param updateSupport
     * @param operName
     * @return
     */
    @Override
    public String importData(List<ZnSupplier> znSupplierList, String type, boolean updateSupport, String operName) {
        int successNum = 0;
        int failureNum = 0;
        int repeatNum = 0;
        int index = 1;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        StringBuilder repeatMsg = new StringBuilder();
        Date now = new Date();
        try
        {
            //HashSet<String> telephoneList = redisCache.getCacheObject(RedisConstant.USER_ID_CARD_NO);
            HashSet<String> telephoneSet = null;
//          logger.debug("redis查询完成");
            HashSet waitList = new HashSet();//待入库
            if(telephoneSet==null){
                telephoneSet = new HashSet<>();
                ZnSupplier znSupplier = new ZnSupplier();
                znSupplier.setTenantId(SecurityUtils.getTenantId());
                znSupplier.setType(type);
                List<ZnSupplier> list = znSupplierMapper.selectZnSupplierList(znSupplier);
                for (ZnSupplier temp:list) {
                    telephoneSet.add(temp.getTelephone());
                }
            }

            List<ZnSupplier> importList = new ArrayList<>();
            for (ZnSupplier znSupplier : znSupplierList)
            {
                if(StringUtils.isEmpty(znSupplier.getSupplier()) || StringUtils.isEmpty(znSupplier.getTelephone())){
                    failureNum++;
                    if(StringUtils.isEmpty(znSupplier.getSupplier()) && StringUtils.isEmpty(znSupplier.getTelephone())){
                        failureMsg.append("<br/>" + failureNum + "、第"+index+"行，信息（名称，电话为必填内容）不能为空");
                    }else{
                        if(StringUtils.isEmpty(znSupplier.getSupplier())){
                            failureMsg.append("<br/>" + failureNum + "、第"+index+"行，信息（手机号码：" + znSupplier.getTelephone() + "）的名称不能为空");
                        }else if(StringUtils.isEmpty(znSupplier.getTelephone())){
                            failureMsg.append("<br/>" + failureNum + "、第"+index+"行，信息（名称：" + znSupplier.getSupplier() + "）的手机号码不能为空");
                        }
                    }
                }else{//姓名、身份证不能为空,并使用手机号码作为唯一的识别key
                    if (!telephoneSet.contains(znSupplier.getTelephone()))
                    {

                        znSupplier.setTenantId(SecurityUtils.getTenantId());
                        znSupplier.setEnabled(0);
                        znSupplier.setDeleteFlag("0");
//                        znSupplier.setIsystem(1);
                        znSupplier.setType(type);
                        waitList.add(znSupplier.getTelephone());
                        importList.add(znSupplier);
                        successNum++;
                    }else{
                        repeatNum++;
                        failureMsg.append("<br/>" + repeatNum + "、第"+index+"行，信息（手机号码：" + znSupplier.getTelephone() + "） 已存在");
                    }
                }
                index++;

            }

            if (failureNum > 0 || repeatNum > 0)
            {
                String  msg = "";
                if(successNum>0){
                    msg ="已成功导入数据，共 " + successNum + " 条；";
                }
                msg  += "导入失败数据，共 "+ (failureNum+repeatNum)+" 条，其中， ";
                if (failureNum > 0)
                {
                    msg +=" 数据不完整 " + failureNum + " 条，";
                }
                if (repeatNum > 0)
                {
                    msg +=" 数据已存在 " + repeatNum + " 条，";
                }
                msg += "错误如下：";
                failureMsg.insert(0, msg);
                return repeatMsg.toString()+failureMsg.toString();
            }else{
                //java8 去重名字相同
                logger.debug("第一次去重前数量："+importList.size());
                importList = importList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(ZnSupplier::getSupplier))),ArrayList::new));
                logger.debug("第一次去重后数量："+importList.size());
                importList = importList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(ZnSupplier::getTelephone))),ArrayList::new));
//              logger.debug("第二次去重后数量："+importList.size());
                logger.debug("待导入数量："+importList.size());
                int pageSize = 800;
                if(importList.size()>pageSize){
                    int pageNum = importList.size()/pageSize ;
                    logger.debug("本次导入数量："+importList.size());
                    pageNum = (importList.size()> pageNum*pageSize)?(pageNum+1) : pageNum;
                    logger.debug("导入次数："+pageNum);
                    int i = 1;
                    while(i<=pageNum){
                        logger.debug("页数："+i+"。"+(i-1)*pageSize +"-"+ (i==pageNum?importList.size():i*pageSize));
                        znSupplierMapper.batchInsertZnSupplier(importList.subList((i-1)*pageSize,(i==pageNum?importList.size():i*pageSize)));
                        i++;
                    }
                }else if(importList.size()>0){
                    znSupplierMapper.batchInsertZnSupplier(importList);
                }
                successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
            }
        }
        catch (Exception e)
        {
            failureNum++;
            String msg = "<br/>" + failureNum + "、第"+index+"行，导入异常。";
            failureMsg.append(msg + e.getMessage());
            e.printStackTrace();
        }
        return successMsg.toString();
    }

    /**
     * 供应商、客户、会员等信息下拉框数据查询
     * 客户数据是有受系统配置影响，如果有开启限制，只能看到分配的客户、自己创建的客户
     * @param znSupplier
     * @return
     */
    @Override
    public List<ZnSupplier> selectZnSupplierSelectList(ZnSupplier znSupplier) {
        List<ZnSupplier> list =  znSupplierMapper.selectZnSupplierList(znSupplier);
        List<ZnSupplier> result = new ArrayList<>();
        if(list.size()>0){
            if(StringUtils.isNotBlank(znSupplier.getType()) && "客户".equals(znSupplier.getType())){
                ZnCompanyConfig znCompanyConfig=znCompanyConfigService.selectZnCompanyConfigBytenantId(SecurityUtils.getTenantId());
                boolean customerFlag ="1".equals(znCompanyConfig.getCustomerFlag())?true:false; //获取系统配置，是否需要用户需要分配客户，暂时先写false
                if(customerFlag) {
                    SaveBusinessVO saveBusinessVO =new SaveBusinessVO();
                    saveBusinessVO.setUserId(SecurityUtils.getUserId());
                    saveBusinessVO.setType("UserCustomer");
                    saveBusinessVO.setTenantId(SecurityUtils.getTenantId());
                    ZnUserBusiness znUserBusiness = znUserBusinessService.selectZnUserBusinessByUserIdAndType(saveBusinessVO);
                    List<Long> values=new ArrayList<>();
                    if(null!=znUserBusiness&&znUserBusiness.getValue()!=null){
                        String[] strs =   znUserBusiness.getValue().split(",");
                        for (ZnSupplier supplier : list) {
                            for(String supplierId:strs){
                                if(supplier.getId() == Long.parseLong(supplierId)){
                                    result.add(supplier);
                                }
                            }
                        }
                    }
                }else{
                    result.addAll(list);
                }
            }else{
                result.addAll(list);
            }
        }

        return result;
    }
}
